package com.tiny.myagent.util;

import android.content.Context;
import android.os.PowerManager;
import android.util.Log;

import com.tiny.myagent.enums.BootAction;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BootUtil {


    /**
     * {@link android.os.PowerManager#reboot}
     *
     * @param action shutdown:关机，reboot：重启
     */
    public static void downAndReboot(BootAction action) {
        try {
            Object oIPowerManager = getPowerManager();

            Method method = oIPowerManager.getClass().getMethod(action.getAction(), boolean.class, String.class, boolean.class);
            method.invoke(oIPowerManager, false, action.getRemark(), true);


        } catch (Exception e) {
            Log.e("BootUtil", e.toString(), e);
        }
    }

    public static Object getPowerManager() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException {


        //获得ServiceManager类
        Class<?> ServiceManager = Class.forName("android.os.ServiceManager");

        //获得ServiceManager的getService方法
        Method getService = ServiceManager.getMethod("getService", java.lang.String.class);

        //调用getService获取RemoteService
        Object oRemoteService = getService.invoke(null, Context.POWER_SERVICE);

        //获得IPowerManager.Stub类
        Class<?> cStub = Class.forName("android.os.IPowerManager$Stub");
        //获得asInterface方法
        Method asInterface = cStub.getMethod("asInterface", android.os.IBinder.class);
        //调用asInterface方法获取IPowerManager对象

        return asInterface.invoke(null, oRemoteService);
    }
}
